// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/buffer/buffer.h>

namespace kumo::pollux {
    namespace {
        struct BufferReleaser {
            explicit BufferReleaser(const BufferPtr &parent) : parent_(parent) {
            }

            void addRef() const {
            }

            void release() const {
            }

        private:
            BufferPtr parent_;
        };
    } // namespace

    BufferPtr Buffer::sliceBufferZeroCopy(
        size_t typeSize,
        bool podType,
        const BufferPtr &buffer,
        size_t offset,
        size_t length) {
        auto bytesOffset = checkedMultiply(offset, typeSize);
        auto bytesLength = checkedMultiply(length, typeSize);
        POLLUX_CHECK_LE(
            bytesOffset,
            buffer->size(),
            "Offset must be less than or equal to {}.",
            buffer->size() / typeSize);
        POLLUX_CHECK_LE(
            bytesLength,
            buffer->size() - bytesOffset,
            "Length must be less than or equal to {}.",
            buffer->size() / typeSize - offset);
        // Cannot use `Buffer::as<uint8_t>()` here because Buffer::podType_ is false
        // when type is OPAQUE.
        auto data =
                reinterpret_cast<const uint8_t *>(buffer->as<void>()) + bytesOffset;
        return BufferView<BufferReleaser>::create(
            data, bytesLength, BufferReleaser(buffer), podType);
    }

    template<>
    BufferPtr Buffer::slice<bool>(
        const BufferPtr &buffer,
        size_t offset,
        size_t length,
        memory::MemoryPool *pool) {
        POLLUX_CHECK_NOT_NULL(buffer, "Buffer must not be null.");

        if (offset % 8 == 0) {
            return sliceBufferZeroCopy(
                1, true, buffer, bits::nbytes(offset), bits::nbytes(length));
        }
        POLLUX_CHECK_NOT_NULL(pool, "Pool must not be null.");
        auto ans = AlignedBuffer::allocate<bool>(length, pool);
        bits::copyBits(
            buffer->as<uint64_t>(), offset, ans->asMutable<uint64_t>(), 0, length);
        return ans;
    }
} // namespace kumo::pollux
